package com.huatai.user.websocket;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huatai.common.util.CommonUtils;
import com.huatai.user.constant.RedisConstant;
import com.huatai.user.service.ServerInfoService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class SystemMessageWebsocketHandler extends TextWebSocketHandler {
    private static final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

	private StringRedisTemplate redisTemplate;

	private ServerInfoService serverInfoService;

	public SystemMessageWebsocketHandler(StringRedisTemplate redisTemplate, ServerInfoService serverInfoService) {
		this.redisTemplate = redisTemplate;
		this.serverInfoService = serverInfoService;
	}

	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		String pathQuery = session.getUri().getQuery();
		Map<String, String> paramMap = CommonUtils.formatUrlParams(pathQuery);
		String serverIp = paramMap.get("serverIp").replaceAll("\\.","_");
		String ts = paramMap.get("ts");

		String clientIp = (String) session.getAttributes().get("clientIp");

		String sessionKey = serverIp + "-" + clientIp + "-" + ts;

		Integer maxLink = serverInfoService.getMaxLinkValue(serverIp.replaceAll("_","\\."));

		Set<String> keys = redisTemplate.keys(RedisConstant.SERVER_CONNECTION_USERS + serverIp + ":*");

		List<JSONObject> keyList = new ArrayList<>();
		for (String key : keys) {
			JSONObject obj = new JSONObject();
			String[] split = key.split(":");
			obj.put("clientIp",split[2]);
			obj.put("ts",split[3]);
			keyList.add(obj);
		}

		JSONObject result = new JSONObject();
		result.put("max",maxLink);
		if(sessions.get(sessionKey) == null){
			sessions.put(sessionKey, session);
			JSONObject obj = new JSONObject();
			obj.put("clientIp",clientIp);
			obj.put("ts", ts);
			//不存在，新增
			redisTemplate.opsForValue().set(RedisConstant.SERVER_CONNECTION_USERS + serverIp + ":" + clientIp  + ":" + ts, "1");
			keyList.add(obj);
		}

		if(keyList.size() > 0){
			Collections.sort(keyList, Comparator.comparingLong(obj -> {
				try {
					return Long.parseLong(obj.getString("ts"));
				} catch (Exception e) {
					return 0;
				}
			}));
		}

		result.put("userList",keyList);
		//给所有用户推
		sendMessageByServerIp(serverIp,result.toJSONString());
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		String pathQuery = session.getUri().getQuery();
		Map<String, String> paramMap = CommonUtils.formatUrlParams(pathQuery);
		String serverIp = paramMap.get("serverIp").replaceAll("\\.","_");
		String ts = paramMap.get("ts");
		String clientIp = (String) session.getAttributes().get("clientIp");
		String sessionKey = serverIp + "-" + clientIp + "-" + ts;

		String redisKey = RedisConstant.SERVER_CONNECTION_USERS + serverIp + ":" + clientIp  + ":" + ts;
		redisTemplate.delete(redisKey);
		sessions.remove(sessionKey);
		//断开连接以后，需要给所有用户推送最新用户数据
		Set<String> keys = redisTemplate.keys(RedisConstant.SERVER_CONNECTION_USERS + serverIp + ":*");
		Integer maxLink = serverInfoService.getMaxLinkValue(serverIp.replaceAll("_","\\."));
		List<JSONObject> keyList = new ArrayList<>();
		for (String key : keys) {
			JSONObject obj = new JSONObject();
			String[] split = key.split(":");
			obj.put("clientIp",split[2]);
			obj.put("ts",split[3]);
			keyList.add(obj);
		}
		JSONObject result = new JSONObject();
		result.put("max",maxLink);

		if(keyList.size() > 0){
			Collections.sort(keyList, Comparator.comparingLong(obj -> {
				try {
					return Long.parseLong(obj.getString("ts"));
				} catch (Exception e) {
					return 0;
				}
			}));
		}

		result.put("userList",keyList);
		sendMessageByServerIp(serverIp,result.toJSONString());
	}

//    @Override
//    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
//        String pathQuery = session.getUri().getQuery();
//        Map<String, String> paramMap = CommonUtils.formatUrlParams(pathQuery);
//        String serverIp = paramMap.get("serverIp").replaceAll("\\.","_");
//        String ts = paramMap.get("ts");
//
//        String realName = paramMap.get("realName");
//        String userName = paramMap.get("userName");
//		String sessionKey = serverIp + "-" + realName + "-" + userName + "-" + ts;
//
//		Integer maxLink = serverInfoService.getMaxLinkValue(serverIp.replaceAll("_","\\."));
//
//		Set<String> keys = redisTemplate.keys(RedisConstant.SERVER_CONNECTION_USERS + serverIp + ":*");
//
//		List<JSONObject> keyList = new ArrayList<>();
//		for (String key : keys) {
//			JSONObject obj = new JSONObject();
//			String[] split = key.split(":");
//			obj.put("realName",split[2]);
//			obj.put("userName",split[3]);
//			obj.put("ts",split[4]);
//			keyList.add(obj);
//		}
//
//		JSONObject result = new JSONObject();
//		result.put("max",maxLink);
//		if(sessions.get(sessionKey) == null){
//			sessions.put(sessionKey, session);
//			JSONObject obj = new JSONObject();
//			obj.put("realName",realName);
//			obj.put("userName",userName);
//			obj.put("ts", ts);
//			//不存在，新增
//			redisTemplate.opsForValue().set(RedisConstant.SERVER_CONNECTION_USERS + serverIp + ":" + realName + ":" + userName  + ":" + ts, "1");
//			keyList.add(obj);
//		}
//
//		if(keyList.size() > 0){
//			Collections.sort(keyList, Comparator.comparingLong(obj -> {
//				try {
//					return Long.parseLong(obj.getString("ts"));
//				} catch (Exception e) {
//					return 0;
//				}
//			}));
//		}
//
//		result.put("userList",keyList);
//		//给所有用户推
//		sendMessageByServerIp(serverIp,result.toJSONString());
//	}
//
//    @Override
//    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
//		String pathQuery = session.getUri().getQuery();
//		Map<String, String> paramMap = CommonUtils.formatUrlParams(pathQuery);
//		String serverIp = paramMap.get("serverIp").replaceAll("\\.","_");
//		String ts = paramMap.get("ts");
//		String realName = paramMap.get("realName");
//		String userName = paramMap.get("userName");
//		String sessionKey = serverIp + "-" + realName + "-" + userName + "-" + ts;
//
//		String redisKey = RedisConstant.SERVER_CONNECTION_USERS + serverIp + ":" + realName + ":" + userName  + ":" + ts;
//		redisTemplate.delete(redisKey);
//		sessions.remove(sessionKey);
//		//断开连接以后，需要给所有用户推送最新用户数据
//		Set<String> keys = redisTemplate.keys(RedisConstant.SERVER_CONNECTION_USERS + serverIp + ":*");
//		Integer maxLink = serverInfoService.getMaxLinkValue(serverIp.replaceAll("_","\\."));
//		List<JSONObject> keyList = new ArrayList<>();
//		for (String key : keys) {
//			JSONObject obj = new JSONObject();
//			String[] split = key.split(":");
//			obj.put("realName",split[2]);
//			obj.put("userName",split[3]);
//			obj.put("ts",split[4]);
//			keyList.add(obj);
//		}
//		JSONObject result = new JSONObject();
//		result.put("max",maxLink);
//
//		if(keyList.size() > 0){
//			Collections.sort(keyList, Comparator.comparingLong(obj -> {
//				try {
//					return Long.parseLong(obj.getString("ts"));
//				} catch (Exception e) {
//					return 0;
//				}
//			}));
//		}
//
//		result.put("userList",keyList);
//		sendMessageByServerIp(serverIp,result.toJSONString());
//    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

    }

	public static void sendMessageByServerIp(String serverIp, String message) {
		for (String s : sessions.keySet()) {
            if(s.indexOf(serverIp) > -1){
                WebSocketSession session = sessions.get(s);
                if (session == null){
                    continue;
                }
                if (!session.isOpen()) {
                    continue;
                }
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("用户【"+s+"】推送信息失败");
                }
            }
        }
	}

    public static void sendMessageToUser(String userId, String message) {
        WebSocketSession session = sessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
//    /**
//     * 根据用户id发送给某一个用户
//     **/
//    public boolean sendMessageToUser(SystemMessageWebsocketVo websocketVo) {
//        String seatId = websocketVo.getSendKey()+"-";
//        for (String s : sessions.keySet()) {
//            if(s.indexOf(seatId) > -1){
//                WebSocketSession session = sessions.get(s);
//                if (session == null){
//                    continue;
//                }
//                if (!session.isOpen()) {
//                    continue;
//                }
//                try {
//                    String message = JSONObject.toJSONString(websocketVo);
//                    session.sendMessage(new TextMessage(message));
//                } catch (IOException e) {
//                    e.printStackTrace();
//                    System.out.println("用户【"+s+"】推送信息失败");
//                    continue;
//                }
//            }
//        }
//        return true;
//    }


}
